﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using WmWebSystem.Models;
using WmWebSystem.Service;
using WmWebSystem.DbHelper;

namespace WmWebSystem.Controllers
{
    public class ProjectController : Controller
    {
        //
        // GET: /Project/
        WmDb mydb = new WmDb();
        
        public ActionResult List() 
        {
            ViewData["models"] = ProjectHelper.FindAllProjectByStatus(1);
            ViewData["CItems"] = ChildProjectHelper.FindAllMusicItems();

            return View();
        }

        public ActionResult Index()
        {
            WmWebSystem.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Project> datesource = GetDataSource();//要分页的数据源
            Model.ProjectList = datesource.Where(r => r.ProjectId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.ProjectList = datesource.Where(r => r.ProjectId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Project> GetDataSource()
        {
            var Project = from b in mydb.Projects
                       orderby b.AddTime ascending
                       select b;
            List<Project> model = new List<Project>();
            foreach (var item in Project)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(WmWebSystem.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Project> datesource = GetDataSource();//要分页的数据源
            Model.ProjectList = datesource.Where(r => r.ProjectId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        public ActionResult Search()
        {
            string code = Request.Form["p_code"];
            string cont = Request.Form["p_cont"];
            int type = Convert.ToInt32(Request.Form["p_type"].ToString());
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-1-1");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }

            return View(ProjectHelper.FindProjectBySearch(code,start,end, type));

        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        //[HttpPost,HttpGet]
        [ValidateInput(false)]
        [HttpPost]
        [Authorize]
        public ActionResult DoCreate(Project model)
        {
            string P_No = RandomNumberTo.GenerateRandomNumber();
            //string title = Request.Form["projectName"];
            decimal target = Convert.ToDecimal(model.TargetValue);
            //string summary = Request.Form["Summary"];
            int projectType = Convert.ToInt32(Request.Form["projectType"]);
            
            string extension = "";
            string fileOldName = "";
            string status = "";  //1:成功；2：文件格式不正确


            foreach (string created in Request.Files)
            {
                if (!WmWebSystem.Service.HasFiles.HasFile(Request.Files[created])) continue;

                //string mimiType = Request.Files[created].ContentType.ToLower();

                fileOldName = Path.GetFileName(Request.Files[created].FileName);
                extension = System.IO.Path.GetExtension(fileOldName);  //扩展名 ".xxxx"

                if (ProjectService.IsImage(extension))
                {
                    Stream fileStream = Request.Files[created].InputStream;
                    string path = ProjectHelper.CreateNewFolderInProjectContent(P_No);
                    //添加一个判断"ProjectContent"文件夹是否存在的方法
                    string SavePath = HasFolders.HasFolder(AppDomain.CurrentDomain.BaseDirectory + @"ProjectContent\" + P_No + "\\");
                    //string filename = DataManipulation.RandomNumberToName() + "."+mimiType;
                    string filename = Path.GetFileName(Request.Files[created].FileName);
                    //文件重命名
                    string fileNewName = RandomNumberTo.RandomNumberToName() + extension;
                    //文件未重命名
                    //fileOldName = Path.GetFileName(Request.Files[created].FileName);
                    Request.Files[created].SaveAs(Path.Combine(SavePath, fileNewName));

                    string logo = "~\\ProjectContent\\" + P_No + "\\" + fileNewName;
                    string delpath = SavePath + fileNewName;

                    ProjectHelper.CreateNewToProjects(P_No, model.ProjectName, projectType, model.Content, target, logo,delpath);
                    status = "1";
                }
                else
                {
                    status = "2";
                    break;
                }

            }

            if (status == "1")
            {
                if (HttpContext.User.IsInRole("admin") || HttpContext.User.IsInRole("editor"))
                {
                    return RedirectToAction("Index", "Project");
                }
                else 
                {
                    return RedirectToAction("ProjectView", "Project", new { No = P_No });
                }
            }
            else
            {
                string error = "Logo必须为图片文件！如'.jpg/.jpeg/.png/.bmp'";
                return RedirectToAction("Error", "Notice", new { message = error });
            }



        }

        [Authorize]
        [HttpGet]
        public ActionResult ProjectView(string No)
        {
            var project = ProjectHelper.FindProjectByProjectNo(No);

            var childProjects = ChildProjectHelper.FindAllChildProjectsTo(No);

            ViewData["ChildProjects"] = childProjects;
            ViewBag.No = No;

            return View(project);
        }

        public ActionResult ToDetails(string no) 
        {
            var pro = ProjectHelper.FindProjectByProjectNo(no);
            if (pro != null)
            {
                string p_no = pro.ProjectNo;
                var cp = ChildProjectHelper.FindAllChildProjectsTo(p_no);
                ViewData["childProjects"] = cp;
                var comments = CommentHelper.FindByCode(p_no);
                ViewData["comments"] = comments;
                return View(pro);
            }
            else
            {
                string error = "该项目不存在哦！";
                return RedirectToAction("Error", "Notice", new { message = error });
            }
        }

        public ActionResult Details(int id) 
        {
            
            var pro = ProjectHelper.FindProjectById(id);
            if (pro != null)
            {
                string p_no = pro.ProjectNo;
                var cp = ChildProjectHelper.FindAllChildProjectsTo(p_no);
                ViewData["childProjects"] = cp;
                var comments = CommentHelper.FindByCode(p_no);
                ViewData["comments"] = comments;
                return View(pro);
            }
            else 
            {
                string error="该项目不存在哦！";
                return RedirectToAction("Error", "Notice", new { message = error });
            }
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            var pro = ProjectHelper.FindProjectById(id);
            return View(pro);
        }

        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult DoEdit(Project model)
        {
            string type = Request.Form["Ptype"];
            string extension = "";
            string fileOldName = "";
            string status = "";  //1:成功；2：文件格式不正确
            string error = "";
            try
            {
                foreach (string created in Request.Files)
                {
                    if (!WmWebSystem.Service.HasFiles.HasFile(Request.Files[created]))
                    {
                        fileOldName = Path.GetFileName(Request.Files[created].FileName);
                        extension = System.IO.Path.GetExtension(fileOldName);  //扩展名 ".xxxx"

                        if (ProjectService.IsImage(extension))
                        {
                            Stream fileStream = Request.Files[created].InputStream;
                            string path = ProjectHelper.CreateNewFolderInProjectContent(model.ProjectNo);
                            //添加一个判断"ProjectContent"文件夹是否存在的方法
                            string SavePath = HasFolders.HasFolder(AppDomain.CurrentDomain.BaseDirectory + @"ProjectContent\" + model.ProjectNo + "\\");
                            //string filename = DataManipulation.RandomNumberToName() + "."+mimiType;
                            string filename = Path.GetFileName(Request.Files[created].FileName);
                            //文件重命名
                            string fileNewName = RandomNumberTo.RandomNumberToName() + extension;
                            string delpath = SavePath + fileNewName;
                            System.IO.File.Delete(delpath);
                            Request.Files[created].SaveAs(Path.Combine(SavePath, fileNewName));
                            string logo = "~\\ProjectContent\\" + model.ProjectNo + "\\" + fileNewName;

                            model.Logo = logo;
                            model.DelPath = delpath;
                            if (type != "" || type != null)
                            {
                                model.Type = Convert.ToInt32(type);
                            }
                            UpdateModel(model);
                            mydb.SaveChanges();
                            status = "0";
                        }
                        else
                        {
                            status = "1";
                        }
                    }
                    else
                    {
                        if (type != "" || type != null)
                        {
                            model.Type = Convert.ToInt32(type);
                        }
                        UpdateModel(model);
                        mydb.SaveChanges();
                        status = "0";
                    }

                }
            }
            catch (Exception ex) 
            {
                status = "2";
                error = "Has error when Edit Project" + model.ProjectNo + ";" + ex.ToString();
            }
            if (status == "0")
            {
                return RedirectToAction("Details", new { id = model.ProjectId });
            }
            else if (status == "1")
            {
                error = "Logo必须为图片文件！如'.jpg/.jpeg/.png/.bmp'";
                return RedirectToAction("Error", "Notice", new { message = error });
            }
            else
            {
                return RedirectToAction("Error", "Notice", new { message = error });
            }

        }
        [Authorize]
        public ActionResult Delete(int id)
        {
            var pro = ProjectHelper.FindProjectById(id);
            return View(pro);
        }
        [Authorize]
        public ActionResult DoDelete(int id, FormCollection collection)
        {
            var project = mydb.Projects.Find(id);
            if (project.Status > 1) 
            {
                string error = "项目已审批通过，不可删除！请联系管理员！";
                return RedirectToAction("Error","Notice", new { message = error });
            }
            else 
            {
                ProjectHelper.DeleteFromProjects(project.ProjectId);
                return RedirectToAction("MyProject", "Zone");
            }
            
        }

        [HttpGet]
        [Authorize(Roles = "admin")]
        public ActionResult Publish(int id, FormCollection collection)
        {
            var project = ProjectHelper.FindProjectById(id);
            bool success = ChangeTheStatusOfProject(id, 1);
            if (success)
            {
                return ProjectView(project.ProjectNo);
            }
            else
            {
                string msg = "数据访问出错咯！请再试一次吧···";
                return RedirectToAction("Error", "Notice", new { message = msg });
            }

        }

        //修改项目的状态
        public bool ChangeTheStatusOfProject(int id, int status)
        {
            var project = ProjectHelper.FindProjectById(id);
            project.Status = status;
            try
            {
                UpdateModel(project);
                mydb.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult CommentCreate()
        {
            string code = Request.Form["ProjectNo"];
            string cont = Request.Form["CommentTip"];
            int Id = 0;
            if (cont != "" && code != "")
            {
                CommentHelper.AddNew(code, cont);
                return RedirectToAction("Details", new { id = Id });
            }
            else
            {
                return RedirectToAction("Details", new { id = Id });
            }
        }

       
    }
}
